package cn.itsource.controller;

import cn.itsource.domain.IpAddress;
import cn.itsource.service.IpAddressService;
import cn.itsource.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/ipAddress")
public class IpAddressController {

    @Autowired
    private IpAddressService ipAddressService;

    //注意前端地址：http://localhost:8080/ipAddress - get
    //查询所有
    @GetMapping
    public List<IpAddress> findAll(){
        return ipAddressService.findAll();
    }

    //注意前端地址：http://localhost:8080/ipAddress/1 - get
    //根据id查询
    @GetMapping("/{id}")
    public IpAddress findOne(@PathVariable("id") Long id){
        return ipAddressService.findOne(id);
    }

    //注意前端地址：http://localhost:8080/ipAddress/1 - delete
    //根据id删除
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            ipAddressService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"你选择的数据删除失败");
        }
    }


    //注意前端地址：http://localhost:8080/article - put - {}
    //判断ipAddress对象中是否存在id，根据id修改数据，否则添加数据
    @PutMapping
    public AjaxResult addorUpdate(@RequestBody IpAddress ipAddress){
        try {
            if (ipAddress.getId() == null){
                ipAddressService.add(ipAddress);
            }else {
                ipAddressService.update(ipAddress);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"网络繁忙，亲稍后再试");
        }
    }

}
